﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;

namespace O1.IO.Storage
{
    [ContractVerification(true)]
    public abstract class PersistentTrunk : IDisposable
    {
        [CLSCompliant(false)]
        public ushort TrunkId
        {
            get
            {
                return (ushort)this.TrunkIdCore;
            }
        }

        public abstract int CellCount { get; }

        public abstract long SizeInBytes { get; }

        public abstract TrunkFile Primary { get; }

        protected abstract int TrunkIdCore { get; }

        public abstract IEnumerable<TrunkFile> Differences();

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (this.Primary != null)
            {
                this.Primary.Dispose();
            }

            var differences = this.Differences();
            if (differences != null)
            {
                foreach (var stream in differences)
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
        }
    }
}